package com.asj.house.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.asj.house.entity.HouseRoom;
import com.asj.house.entity.HouseRoomMap;
import com.asj.house.mapper.HouseRoomMapMapper;
import com.asj.house.returns.RespCode;
import com.asj.house.returns.RespEntity;
import com.asj.house.returns.RespTable;
import com.asj.house.service.HouseRoomMapService;
import com.asj.house.service.HouseRoomService;
import com.asj.house.vo.param.RoomParam;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 房屋地图信息表 服务实现类
 * </p>
 *
 * @author asj
 * @since 2021-03-16
 */
@Service
public class HouseRoomMapServiceImpl extends ServiceImpl<HouseRoomMapMapper, HouseRoomMap> implements HouseRoomMapService {

    @Autowired
    private HouseRoomService houseRoomService;

    @Override
    public RespTable<List<HouseRoomMap>> listHouseRoomMap(RoomParam roomParam) {
        QueryWrapper<HouseRoom> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(roomParam.getName())) {
            queryWrapper.lambda().like(HouseRoom::getName, roomParam.getName());
        }
        queryWrapper.lambda().orderByDesc(HouseRoom::getId);
        IPage<HouseRoom> iPage = new Page<>(roomParam.getPage(), roomParam.getLimit());
        IPage<HouseRoom> page = houseRoomService.page(iPage, queryWrapper);

        if (CollectionUtil.isEmpty(iPage.getRecords())) {
            return new RespTable<>(RespCode.SUCCESS, new ArrayList<>(), page.getTotal());
        }

        List<HouseRoomMap> houseRoomMapList = Lists.newArrayList();
        for (HouseRoom houseRoom : page.getRecords()) {
            QueryWrapper<HouseRoomMap> mapQueryWrapper = new QueryWrapper<>();
            mapQueryWrapper.lambda().eq(HouseRoomMap::getRoomId, houseRoom.getId());
            HouseRoomMap houseRoomMap = baseMapper.selectOne(mapQueryWrapper);
            houseRoomMap.setRoomName(houseRoom.getName());
            houseRoomMapList.add(houseRoomMap);
        }

        houseRoomMapList = houseRoomMapList.stream()
                .sorted(Comparator.comparing(HouseRoomMap::getRoomId).reversed())
                .collect(Collectors.toList());

        return new RespTable<>(RespCode.OK, houseRoomMapList, page.getTotal());
    }

    @Override
    public RespEntity updateHouseRoomMap(HouseRoomMap houseRoomMap) {
        baseMapper.updateById(houseRoomMap);
        return new RespEntity(RespCode.SUCCESS);
    }
}
